package server

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"github.com/spf13/cobra"
	"log"
	"os"
)

//secret 生成公私钥 pem文件

var SerretCmd = &cobra.Command{
	Use:     "secret",
	Version: version,
	Short:   " Generate a public and private key file",
	Long:    " Generate a public and private key file",
	Run: func(cmd *cobra.Command, args []string) {
		CreateSecret()
	},
}

func CreateSecret() {
	// 生成RSA密钥对，这里使用2048位作为密钥长度
	privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		log.Fatalf("create private key err:%v", err)
	}
	// 从私钥中提取公钥
	publicKey := &privateKey.PublicKey

	// 将私钥编码为PEM格式
	privateKeyPem := &pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
	}
	// 写私钥到文件
	privateKeyFile, err := os.Create("private_key.pem")
	if err != nil {
		log.Fatalf("写入私钥文件失败: %v", err)
	}
	defer privateKeyFile.Close()
	err = pem.Encode(privateKeyFile, privateKeyPem)
	if err != nil {
		log.Fatalf("编码并写入私钥失败: %v", err)
	}
	fmt.Println("私钥已保存至 private_key.pem 文件")

	// 将公钥编码为PEM格式
	publicKeyPem := &pem.Block{
		Type:  "PUBLIC KEY",
		Bytes: x509.MarshalPKCS1PublicKey(publicKey),
	}
	// 写公钥到文件
	publicKeyFile, err := os.Create("public_key.pem")
	if err != nil {
		log.Fatalf("创建公钥文件失败: %v", err)
	}
	defer publicKeyFile.Close()
	err = pem.Encode(publicKeyFile, publicKeyPem)
	if err != nil {
		log.Fatalf("编码并写入公钥失败: %v", err)
	}

	fmt.Println("公钥已保存至 public_key.pem 文件")

}
